package br.edu.utfpr.md.tads.controller;

import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import br.edu.utfpr.md.tads.model.Contato;

public class Buscar {

	private HttpClient httpClient = new DefaultHttpClient();
	
	public Buscar(){
	}
	private String get() {
	    try {
	        HttpGet request = new HttpGet("http://192.168.6.98:8080/EasyPhoneServer/rest/pessoa/json");
	        HttpResponse res = httpClient.execute(request);
	        String content = EntityUtils.toString(res.getEntity());
	        return content;
	    } catch (Exception ex) {
	        ex.printStackTrace();
	        return null;
	    }
	}

	public ArrayList<Contato> getContatos(){
		return parserContato(get());
	}

	private ArrayList<Contato> parserContato(String content){
		ArrayList<Contato> contatos = new ArrayList<Contato>();
		if(content != null){
			try{
			JSONObject object = (JSONObject) new JSONTokener(content).nextValue();
			JSONArray jAC = object.getJSONArray("contato");
			for (int i = 0; i < jAC.length(); i++) {
				JSONObject obt = jAC.getJSONObject(i);
				Contato contato = new Contato();
				contato.setNome(obt.getString("nome"));
				contato.setEndereco(obt.getString("endereco"));
				contatos.add(contato);
			}
			}catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
		return contatos;
	}
}
